import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/change-password',
    name: 'ChangePassword',
    component: () => import('@/views/ChangePassword.vue'),
    meta: { title: '修改密码', skipGuard: true }
  },
  {
    path: '/complete-info',
    name: 'CompleteInfo',
    component: () => import('@/views/CompleteInfo.vue'),
    meta: { title: '完善信息', skipGuard: true }
  },
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/Home.vue'),
        meta: { title: '首页' }
      },
      // 学生端专用页面
      {
        path: '/student/dashboard',
        name: 'StudentDashboard',
        component: () => import('@/views/student/Dashboard.vue'),
        meta: { title: '学生首页', roles: ['student'] }
      },
      // 家长端专用页面
      {
        path: '/parent/dashboard',
        name: 'ParentDashboard',
        component: () => import('@/views/parent/Dashboard.vue'),
        meta: { title: '家长首页', roles: ['parent'] }
      },
      {
        path: '/student/apply',
        name: 'StudentApply',
        component: () => import('@/views/student/MyApply.vue'),
        meta: { title: '我的申请', roles: ['student'] }
      },
      {
        path: '/student/scores',
        name: 'StudentScores',
        component: () => import('@/views/student/MyScores.vue'),
        meta: { title: '我的成绩', roles: ['student'] }
      },
      {
        path: '/student/profile',
        name: 'StudentProfile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人信息', roles: ['student'] }
      },
      // 学生管理（管理员/教师使用）
      {
        path: '/student/manage',
        name: 'StudentManage',
        component: () => import('@/views/student/index.vue'),
        meta: { title: '学生管理', roles: ['admin', 'teacher'] }
      },
      // 院系管理
      {
        path: '/dept',
        name: 'Dept',
        component: () => import('@/views/Dept/index.vue'),
        meta: { title: '院系管理', roles: ['admin'] }
      },
      // 班级管理
      {
        path: '/class',
        name: 'Class',
        component: () => import('@/views/Class/index.vue'),
        meta: { title: '班级管理', roles: ['admin'] }
      },
      // 成绩管理
      {
        path: '/score',
        name: 'Score',
        component: () => import('@/views/Score/index.vue'),
        meta: { title: '成绩管理', roles: ['admin', 'teacher'] }
      },
      // 档案记录
      {
        path: '/record',
        name: 'Record',
        component: () => import('@/views/Record/index.vue'),
        meta: { title: '档案记录', roles: ['admin', 'teacher'] }
      },
      // 用户管理
      {
        path: '/user',
        name: 'User',
        component: () => import('@/views/User/index.vue'),
        meta: { title: '用户管理', roles: ['admin'] }
      },
      // 审批中心
      {
        path: '/approval',
        name: 'Approval',
        component: () => import('@/views/Approval/index.vue'),
        meta: { title: '审批中心', roles: ['admin', 'teacher'] }
      },
      // 导入导出
      {
        path: '/import-export',
        name: 'ImportExport',
        component: () => import('@/views/ImportExport/index.vue'),
        meta: { title: '导入导出', roles: ['admin', 'teacher'] }
      },
      // 消息中心
      {
        path: '/message',
        name: 'Message',
        component: () => import('@/views/Message/index.vue'),
        meta: { title: '消息中心' }
      },
      // 个人信息
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人信息' }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 学生档案管理系统` : '学生档案管理系统'
  
  // 登录页、修改密码页和完善信息页直接放行
  if (to.path === '/login' || to.path === '/change-password' || to.path === '/complete-info') {
    next()
    return
  }
  
  // 未登录跳转到登录页
  if (!userStore.token) {
    next('/login')
    return
  }
  
  // 确保 userInfo 已加载
  if (!userStore.userInfo) {
    // 尝试从 localStorage 恢复
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo) {
      try {
        userStore.setUserInfo(JSON.parse(savedUserInfo))
      } catch (e) {
        console.error('恢复用户信息失败', e)
        next('/login')
        return
      }
    } else {
      next('/login')
      return
    }
  }
  
  // 检查是否需要修改密码（首次登录）
  if (userStore.userInfo?.needChangePassword === 1 && to.path !== '/change-password') {
    ElMessage.warning('首次登录需要修改密码')
    next('/change-password')
    return
  }
  
  // 检查学生是否需要完善信息（仅学生角色，且已修改密码）
  if (
    userStore.userInfo?.roleCode === 'student' &&
    userStore.userInfo?.needChangePassword === 0 &&
    userStore.userInfo?.infoCompleted === 0 &&
    to.path !== '/complete-info'
  ) {
    ElMessage.info('请完善您的个人信息和绑定家长')
    next('/complete-info')
    return
  }
  
  // 根据角色重定向首页
  if (to.path === '/' || to.path === '/home') {
    const userRole = userStore.userInfo?.roleCode
    if (userRole === 'student') {
      // 学生跳转到学生首页
      next('/student/dashboard')
      return
    } else if (userRole === 'parent') {
      // 家长跳转到家长首页
      next('/parent/dashboard')
      return
    } else {
      // 管理员和教师跳转到默认首页
      if (to.path === '/') {
        next('/home')
        return
      }
    }
  }
  
  // 角色权限检查
  if (to.meta.roles) {
    const roles = to.meta.roles as string[]
    const userRole = userStore.userInfo?.roleCode
    
    // 调试日志
    console.log('路由权限检查:', {
      path: to.path,
      requiredRoles: roles,
      userRole: userRole,
      userInfo: userStore.userInfo
    })
    
    if (!userRole) {
      ElMessage.error('用户角色信息缺失')
      next('/login')
      return
    }
    
    if (!roles.includes(userRole)) {
      ElMessage.error('权限不足')
      // 根据角色跳转到对应首页
      if (userRole === 'student') {
        next('/student/dashboard')
      } else if (userRole === 'parent') {
        next('/parent/dashboard')
      } else {
        next(from.path || '/home')
      }
      return
    }
  }
  
  next()
})

export default router

